package com.mbds.map;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * The person which are connected on the device
 * If a person not make any sign of if life, we remove this person of the network
 */
public class NetWork {
	private static NetWork singleton;
	private static final int DELAY_TO_DECREASE_TTL = 60000; //we decrease the TTL every minute
	
	private Map<String,Person> persons;
	private Timer timer;
	private TimerTask decreaseTTLTasks;
	
	private NetWork() {
		persons = new HashMap<String,Person>();
		timer = new Timer();
		decreaseTTLTasks = new TimerTask() {
			
			@Override
			public void run() {
				for (String pseudo : persons.keySet()) {
					persons.get(pseudo).decreaseTTL();
				}
				
			}
		};
		
		timer.schedule(decreaseTTLTasks, 0,DELAY_TO_DECREASE_TTL);
	}
	
	public static void init() {
		if(singleton == null) {
			singleton = new NetWork();
		}
	}
	
	public static NetWork getInstance() {
		return singleton;
	}
	
	synchronized public boolean addPerson(String pseudo,double lat, double lng) {
		return (persons.put(pseudo, new Person(lat, lng, pseudo)) != null);
	}
	
	synchronized public void maj() {
		for (String pseudo : persons.keySet()) {
			Person p = persons.get(pseudo);
			if(p.getTTL() < 0) {
				persons.remove(p);
			}
		}
	}
	
	synchronized public void resetTTL(String pseudo) {
			persons.get(pseudo).resetTTL();
	}
	
	synchronized public Person getPerson(String pseudo) {
		Person p = persons.get(pseudo);
		return new Person(p.getPosition().latitude, p.getPosition().longitude, p.getPseudo());
	}
	
	synchronized public void removePerson(String pseudo) {
		persons.remove(pseudo);
	}

	synchronized public Collection<Person> getPersons() {
		Collection<Person> ps = new ArrayList<Person>();
		Person p;
		for (String pseudo : persons.keySet()) {
			p = persons.get(pseudo);
			ps.add(new Person(p.getPosition().latitude, p.getPosition().longitude, p.getPseudo()));
		}
		return ps;
	}

}
